(function ($) {
	AjaxSolr.TagcloudWidget = AjaxSolr.AbstractFacetWidget.extend({
		init: function() {
			$(this.target).html(AjaxSolr.theme('no_facets'));
		},
		afterRequest: function () {
			var plainField = this.field.replace(/^\{.*\}/,"");
			if (this.manager.response.facet_counts.facet_fields[plainField] === undefined) {
				$(this.target).html(AjaxSolr.theme('no_facets'));
				return;
			}

			var maxCount = 0;
			var objectedItems = [];
			for (var facet in this.manager.response.facet_counts.facet_fields[plainField]) {
				var count = parseInt(this.manager.response.facet_counts.facet_fields[plainField][facet]);
				if (count > maxCount) {
					maxCount = count;
				}
				objectedItems.push({ facet: facet, count: count });
			}
			objectedItems.sort(function (a, b) {
				return a.facet < b.facet ? -1 : 1;
			});

			$(this.target).empty();
			for (var i = 0, l = objectedItems.length; i < l; i++) {
				var facet = objectedItems[i].facet;
				$(this.target).append(AjaxSolr.theme('tag', {value:facet,count:objectedItems[i].count}, parseInt(objectedItems[i].count / maxCount * 10), this.clickHandler(facet))).append(' ');
			}
			if(objectedItems.length==0) {
				$(this.target).html(AjaxSolr.theme('no_facets'));
			}
		}
	});
})(jQuery);
